﻿#if !UNITY_IOS || HUpdate
using System.IO;
using UnityEngine;

namespace UnityModule
{
    public partial class DownloadComponent
    {
        public static float ShowPercent = 1f;

        //----------
        /// <summary>
        /// 容错次数
        /// </summary>
        private const int CAN_ERROR_NUM = 10;

        //----------

        /// <summary>
        /// 前置下载总大小
        /// </summary>
        public long PreTotalDownBytes { get; private set; }

        /// <summary>
        /// 前置已经接受的大小
        /// </summary>
        public long PreReceivedBytes { get; private set; }

        /// <summary>
        /// 前置下载总数量
        /// </summary>
        public int PreNeedDownloadNum { get; private set; }

        /// <summary>
        /// 已经完成的前置下载文件数量
        /// </summary>
        public int PreCompleteDownloadNum { get; private set; } = 0;

        /// <summary>
        /// 前置下载已经完成
        /// </summary>
        public bool IsPreDownloadFinished
        {
            get
            {
                return PreNeedDownloadNum <= PreCompleteDownloadNum;
            }
        }

        /// <summary>
        /// 总的下载错误次数
        /// </summary>
        //private int m_TotalErrorNum = 0;

        private void PreDownload()
        {
            //DeleteAllCacheFile();//Test: 删除所有文件, 每次都下载
            //全速下载
            IsFullSpeed = true;

            PreDownloadRes();
        }

        private void PreDownloadRes()
        {
            PreTotalDownBytes = 0;
            PreReceivedBytes = 0;
            PreNeedDownloadNum = m_preDownloadList.Count;
            PreCompleteDownloadNum = 0;

            if (PreNeedDownloadNum > 0)
            {
                dlWatcher.Start();
                foreach (var item in m_preDownloadList)
                {
                    //测试下载大文件
                    //if (item.abNameWithHash.Contains("unity"))
                    {
                        PreTotalDownBytes += item.fs;
                        AddPreDownloadTask(item);
                    }

                }
            }
            else
            {
                OnPreDownloadAllFinish();
            }
        }


        /// <summary>
        /// 添加激活时需要的下载
        /// </summary>
        /// <param name="abNameWithHash"></param>
        private void AddPreDownloadTask(AssetBundleInfoV2 assetBundle)
        {
            AddDownloadTask(assetBundle, OnPreDownloaded, OnPreDownloadProgress, true);
        }
        object locker = new object();

        //预下载单个下载任务完成回调
        private void OnPreDownloaded(string retAbName, string exception)
        {
            if (string.IsNullOrEmpty(exception))
            {
                //下载成功
                lock (locker)
                    PreCompleteDownloadNum++;
                RefreshPreDownloadProgress();
                //Debug.LogError(PreNeedDownloadNum + " num: " + PreCompleteDownloadNum + "  "+ m_failCount +"  " + m_beforeFinish);
                //提前结束
                if (m_failCount > 0)
                {
                    Pause();
                    OnPreDownloadAllFinish();
                    m_beforeFinish = true;
                    return;
                }

                if (PreNeedDownloadNum <= PreCompleteDownloadNum)
                {
                    OnPreDownloadAllFinish();
                }
            }
            else
            {
                m_failCount += 1;
                OnPreDownloadAllFinish();
            }
        }
   
        static object PreReceivedLocker = new object();
        //预下载单个下载任务进度回调
        private void OnPreDownloadProgress(long downSize, long totalSize)
        {
            lock (PreReceivedLocker)
                PreReceivedBytes += downSize;
            RefreshPreDownloadProgress();
        }

        private void OnPreDownloadAllFinish()
        {
            if (m_beforeFinish)
            {
                return;
            }
            m_OnFinish?.Invoke();
        }

        //重新统计下载错误
        //private void ClearPreDownloadErrorNum()
        //{
        //    m_TotalErrorNum = 0;
        //}

        private void RefreshPreDownloadProgress()
        {
            PanelLoad.Instance.SetDownloadProgress(PreCompleteDownloadNum, PreNeedDownloadNum, (long)(PreReceivedBytes * ShowPercent), (long)(PreTotalDownBytes * ShowPercent));
        }


        //zip
        //预下载单个下载任务完成回调
        private void DLoadZipComplete(string retAbName, string exception)
        {
            //Debug.LogError("DLoadZipComplete");
            if (string.IsNullOrEmpty(exception))
            {
                //下载成功
                lock (locker)
                    PreCompleteDownloadNum++;
                RefreshPreDownloadProgress();


                //Debug.LogError(PreNeedDownloadNum + " num: " + PreCompleteDownloadNum + "  "+ m_failCount +"  " + m_beforeFinish);
                //提前结束
                if (m_failCount > 0)
                {
                    OnPreDownloadAllFinish();
                    m_beforeFinish = true;
                    return;
                }

                PanelLoad.Instance.ShowTxt("资源解压中(不消耗流量)");
                //可异常捕捉写法
                StartCoroutine(new CatchableEnumerator(ZipUtility.UnZipAsync(ApplicationPath.ABCachePath + m_zipName, ApplicationPath.ABCachePath, (a, b) =>
                {
                    //Debug.LogError(a + "  " + b);
                    PanelLoad.Instance.SetProgress(1f * a / b);
                    if (a >= b)
                    {
                        //Debug.LogError("Finish!");
                        OnPreDownloadAllFinish();
                        //delete
                        if (File.Exists(ApplicationPath.ABCachePath + m_zipName))
                            File.Delete(ApplicationPath.ABCachePath + m_zipName);
                    }
                }), Catched));
            }
            else
            {
                m_failCount += 1;
                OnPreDownloadAllFinish();
            }
        }

        private void Catched()
        {
            //Debug.LogError("Catched!");
            Report.SendEvent((int)ReportStep.ReqZip, "Catch"+ m_zipName);
            m_failCount += 1;
            OnPreDownloadAllFinish();
        }

        //预下载单个下载任务进度回调
        private void DLoadZipProgress(long downSize, long totalSize)
        {
            //Debug.LogError(downSize);
            lock (PreReceivedLocker)
                PreReceivedBytes += downSize;
            PreTotalDownBytes = totalSize;
            RefreshPreDownloadProgress();
        }
    }
}
#endif